package en.edu.zucc.pb.loginapplication.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;

import java.util.List;
import java.util.concurrent.ExecutionException;

import en.edu.zucc.pb.loginapplication.AppDatabase;
import en.edu.zucc.pb.loginapplication.R;
import en.edu.zucc.pb.loginapplication.common.Commons;
import en.edu.zucc.pb.loginapplication.dao.RecordDao;
import en.edu.zucc.pb.loginapplication.dao.UserDao;
import en.edu.zucc.pb.loginapplication.db.Repository;
import en.edu.zucc.pb.loginapplication.entity.Record;
import en.edu.zucc.pb.loginapplication.entity.User;
import en.edu.zucc.pb.loginapplication.repository.UserRepository;
import en.edu.zucc.pb.loginapplication.util.Security;
import en.edu.zucc.pb.loginapplication.viewmodel.UserViewModel;

public class SettingActivity extends AppCompatActivity implements
        View.OnClickListener {

    Button btnToHome;
    LinearLayout main_content;

    private UserViewModel userViewModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_main);
        setContentView(R.layout.activity_setting);
//        setContentView(R.layout.activity_register);
        Log.e("tag", "finished");
//        btnToHome = findViewById(R.id.btn_to_home);
////        btnToHome.
////        https://blog.csdn.net/weixin_33810006/article/details/93024770
//        btnToHome.setOnClickListener(new Button.OnClickListener() {
//            public void onClick(View v) { //使用匿名的Button实例
//
//                //抽象接口的内部方法的实现
//                Intent intent = new Intent(RegisterActivity.this, HomeActivity.class);
//                startActivity(intent);
//            }
//        });
//        btnToHome
//        btn_to_bookkeeping

//        findViewById(R.id.btn_to_bookkeeping).setOnClickListener(this);
//        findViewById(R.id.btn_register).setOnClickListener(this);
//        findViewById(R.id.btnTestDb).setOnClickListener(this);
//        findViewById(R.id.link_signup).setOnClickListener(this);
//        Stetho.initializeWithDefaults(this);
//        https://blog.csdn.net/code_hero666/article/details/80282394


//        main_content = findViewById(R.id.main_content);
//        main_content.getChildAt()
//        initDatabase();

//        userViewModel = new ViewModelProvider(this).get(UserViewModel.class);
    }

//    虽然可以跳转 但是找不到 所以 View 还是要写的
//    public void btn_to_bookkeeping() {
    public void btn_to_bookkeeping(View view) {
        Intent intent = new Intent(this, BookkeepingActivity.class);
        startActivity(intent);
    }

    public void btnClearSoundAndPic(View view) {

    }



    //    必须要public 这样 我这里也可以 ctrl + 鼠标左键 跳转过去了
    public void btn_to_home(View view) {
        Intent intent = new Intent(this, LoginActivity.class);
        startActivity(intent);
    }

    private CheckBox shakeItCb;

    public void shakeItToggle(View view) {
        shakeItCb = (CheckBox) view;
//        shakeItCb=findViewById(R.id.shakeItCb);
//        this.
        if (shakeItCb.isChecked()) {
            editor.putBoolean(Commons.SHAKE_IT, true);
        } else {
            editor.putBoolean(Commons.SHAKE_IT, false);
        }
    }

    public void checkBoxToggle(View view) {
        CheckBox checkBox = (CheckBox) view;
//        shakeItCb=findViewById(R.id.shakeItCb);
//        this.
        pref = PreferenceManager.getDefaultSharedPreferences(this);
//        PreferenceManager 默认 bool 是 true
        editor = pref.edit();

        //获取配置值
//        PreferenceManager.setDefaultValues(this , R.xml.preference , false);
//        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
//————————————————
//        版权声明：本文为CSDN博主「康耶」的原创文章，遵循CC 4.0 BY-SA版权协议，转载请附上原文出处链接及本声明。
//        原文链接：https://blog.csdn.net/qwer492915298/article/details/88063854

        Log.i(TAG, "checkBoxToggle");
        Log.i(TAG, "checkBox.isChecked()  " + checkBox.isChecked());
        switch (checkBox.getId()) {
            case R.id.shakeItCb:
                Log.i(TAG, "SHAKE_IT");

                editor.putBoolean(Commons.SHAKE_IT, checkBox.isChecked());
//                boolean shakeIt = pref.getBoolean(Commons.SHAKE_IT, false);
//                Log.i(TAG, "shakeIt read "+shakeIt);
                break;
            case R.id.NIGHT_MODE_cb:
                editor.putBoolean(Commons.NIGHT_MODE, checkBox.isChecked());
                Log.i(TAG, "NIGHT_MODE");
//                boolean NIGHT_MODE = pref.getBoolean(Commons.NIGHT_MODE, false);
//                Log.i(TAG, "NIGHT_MODE read "+NIGHT_MODE);
                break;
            case R.id.daily_bookkeeping_reminder_cb:
                Log.i(TAG, "daily_bookkeeping_reminder");
                editor.putBoolean(Commons.daily_bookkeeping_reminder, checkBox.isChecked());
//                boolean daily_bookkeeping_reminder =
//                        pref.getBoolean(Commons.daily_bookkeeping_reminder, false);
//                Log.i(TAG, "daily_bookkeeping_reminder read "+daily_bookkeeping_reminder);
                break;
//                if (shakeItCb.isChecked()) {
//                    editor.putBoolean(Commons.SHAKE_IT,true);
//                }else{
//                    editor.putBoolean(Commons.SHAKE_IT,false);
//                }
        }
        editor.apply();
        boolean shakeIt = pref.getBoolean(Commons.SHAKE_IT, false);
        Log.i(TAG, "shakeIt read "+shakeIt);
        boolean NIGHT_MODE = pref.getBoolean(Commons.NIGHT_MODE, false);
        Log.i(TAG, "NIGHT_MODE read "+NIGHT_MODE);
        boolean daily_bookkeeping_reminder =
                pref.getBoolean(Commons.daily_bookkeeping_reminder, false);
        Log.i(TAG, "daily_bookkeeping_reminder read "+daily_bookkeeping_reminder);
    }

    private SharedPreferences.Editor editor;

//    void pref(){
//        pref = PreferenceManager.getDefaultSharedPreferences(this);
//        editor = pref.edit();
//        if(rememberPass.isChecked()){
//            //检查复选框是否被选中
//            editor.putBoolean(Commons.SHAKE_IT,true);
//            editor.putBoolean(Commons.NIGHT_MODE,true);
//            editor.putBoolean(Commons.daily_bookkeeping_reminder,true);
////            editor.putString("account",account);
////            editor.putString("password",password);
//        }else{
//            editor.clear();
//        }
//        editor.commit();
//
//
//    }

    private SharedPreferences pref;
    //    Shake it;
//    摇一摇
//    private static final String  SHAKE_IT= "SHAKE_IT";
//因为这个 app 都要用到 所以还是放在 commons好
    private AppDatabase database;
    UserDao userDao;
    UserRepository userRepository;

//    void initDatabase() {
//
//        database = AppDatabase.getDatabase(getApplicationContext());
//        userDao = database.getUserDao();
//        //获取Database
////        AppDatabase db = Room.databaseBuilder(getApplicationContext(),
////                AppDatabase.class, DATABASE_NAME).build();
//
//        userRepository = new UserRepository(this);
//    }

    private static final String TAG = "LoginActivity";

//    void login() {
//
//        TextView input_email = findViewById(R.id.input_email);
//        String username = input_email.getText().toString();
//        TextView input_password = findViewById(R.id.input_password);
//        String password = input_password.getText().toString();
////room select 不用写代码 和 jpa
////        List<User> byUsername = userDao.getByUsername(username);
//        List<User> byUsername = userRepository.getByUsername(username);
//        if (byUsername == null || byUsername.size() <= 0) {
//            return;
//        }
//        User user = byUsername.get(0);
//        String savedPassword = user.getPassword();
//
////        String oldPassword = Prefs.getString(PREF_PASSWORD, "");
////        String password = passwordEditText.getText().toString();
//        // The check is done on password's hash stored in preferences
//        boolean pswdOk = Security.md5(password).equals(savedPassword);
////          点击确认密码之后 验证一下
//        if (!pswdOk) {
//            String msg = "密码不正确";
//            Log.i(TAG, msg);
//            Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
//            return;
//        }
//        Intent intent = new Intent(this, BookkeepingActivity.class);
//        startActivity(intent);
//    }

//    void signUp() {
//        Intent intent = new Intent(this, BookkeepingActivity.class);
//        startActivity(intent);
//    }

//    private static class DatabaseTestTask extends AsyncTask<Void, Void, Integer> {
//        private AppDatabase database;
//
//        public DatabaseTestTask(AppDatabase db) {
//            this.database = db;
//        }
//
//        @Override
//        protected Integer doInBackground(Void... params) {
//            RecordDao recordDao = database.getRecordDao();
////            BookDao bookDao = database.bookDao();
//
//            //清空既有数据
////            bookDao.clearAll();
////            authorDao.clearAll();
//
//            //插入作者
//            Record record = new Record();
//            record.setMemo("1");
//            long recordId = recordDao.insert(record);
////            long authorid = authorDao.insert(author);
//            Log.d("author add:", record.toString());
//
//            System.out.println("record 1 Id  " + recordId);
//            Record record2 = new Record();
//            record2.setMemo("2");
//            recordDao.insert(record);
//            Log.d("record2 add:", record2.toString());
//
//            List<Record> all = recordDao.getAll();
//            System.out.println("all: " + all);
//            Record byId = recordDao.getById(recordId);
////            刚才插入了 2个，现在插入两个 他是 id 3 那没有错啊
////            I/System.out: record 1 Id  3
////            但是没有搜索出来
//            byId.setMemo("1 up");
//            recordDao.update(byId);
//
//            Record byIdUp = recordDao.getById(recordId);
//            Log.d("byIdUp :", byIdUp.toString());
//
//
//            recordDao.delete(byIdUp);
//            Record byIdDel = recordDao.getById(recordId);
//
//            Log.d("byIdDel :", byIdDel.toString());
////删除了 之后他是 null 确实
//            return 0;
//        }
//
//        @Override
//        protected void onPostExecute(Integer agentsCount) {
//
//        }
//    }

//    private static class DatabaseTask extends AsyncTask<Void, Void, List<User>> {
//        private AppDatabase database;
//        private String username;
//
//        public DatabaseTask(AppDatabase db) {
//            this.database = db;
//        }
//
//        public String getUsername() {
//            return username;
//        }
//
//        public void setUsername(String username) {
//            this.username = username;
//        }
//
//        @Override
//        protected List<User> doInBackground(Void... params) {
////            AuthorDao authorDao = database.authorDao();
////            BookDao bookDao = database.bookDao();
//            UserDao userDao = database.getUserDao();
////            userDao.
//            List<User> byUsername = userDao.getByUsername(username);
////            RegisterActivity.this.userDao.
//
//            return byUsername;
//        }
//
////        java.time.format.TextStyle
//
//    }

//    void testDb() {
//
//        DatabaseTestTask databaseTestTask = new DatabaseTestTask(database);
//        databaseTestTask.execute();
////        Repository repository=new Repository();
//
//    }

    void register() throws ExecutionException, InterruptedException {

        TextView input_email = findViewById(R.id.input_email);
        final String username = input_email.getText().toString();
        TextView input_password = findViewById(R.id.input_password);
        String password = input_password.getText().toString();
//room select 不用写代码 和 jpa
//        List<User> byUsername = userDao.getByUsername(username);
        Log.i(TAG, "username " + username);
//        m 此人是有的 说明 这里没有返回
//        https://blog.csdn.net/weixin_38420342/article/details/105291739
//        LiveData<List<User>> lvdaByUsername = userDao.getLvdaByUsername(username);
//        List<User> byUsername = lvdaByUsername.getValue();
//        Write your db code here
//     final String   usernameFn =username;
//        AsyncTask.execute(new Runnable() { 传递参数


//        AsyncTask.execute(new Runnable() {
//            @Override
//            public void run() {
//                List<User> byUsername = userDao.getByUsername(username);
////                List<User> byUsername = userViewModel.findUserByUsername(username);
////这样还是 ui 线程
////        DatabaseTask databaseTask=new DatabaseTask(database);
////        databaseTask.setUsername(username);
////        AsyncTask<Void, Void, List<User>> execute = databaseTask.execute();
//
////        虽然说这样子可以 但是 每个查询都要写一个类 也太奇怪了
////        List<User> byUsername = execute.get();
//
//                Context context= RegisterActivity.this;
//                if(byUsername==null){
//                    Toast.makeText(context, "查找失败", Toast.LENGTH_SHORT).show();
//                    return;
//                }
////        List<User> byUsername = userRepository.getByUsername(username);
////        https://blog.csdn.net/u012539700/article/details/115833931
////        LiveData
//                if(byUsername.size()>=1){
//                    Toast.makeText(context, "已经有这个用户", Toast.LENGTH_SHORT).show();
//                    return;
//                }
////        if (byUsername == null || byUsername.size() <= 0) {
////            return;
////        }
////        User user = byUsername.get(0);
////        String savedPassword = user.getPassword();
//                User user = new User();
//                user.setUsername(username);
//                user.setPassword(Security.md5(password));
////        long id = userDao.insert(user);
//                userRepository.insert(user);
////     这种没有返回的 倒是可以直接写一个 线程
////        也不行啊 因为具体的东西不一样啊
//
//                Toast.makeText(this, "注册成功 用户名： "+username, Toast.LENGTH_SHORT).show();
//                Intent intent = new Intent(context, LoginActivity.class);
//                startActivity(intent);
//            }
//        });


//        AsyncTask.execute(new AsyncTask<Void, Void, List<User>>() {
//            @Override
//            protected List<User> doInBackground(Void... voids) {
////                https://blog.csdn.net/zxl1173558248/article/details/82492655
//                UserDao userDao = database.getUserDao();
//                List<User> byUsername = userDao.getByUsername(usernameFn);
//
//                return byUsername;
//            }
//
//        });

//        AsyncTask<String, Void, List<User>> execute =

//        List<User> byUsername = new AsyncTask<String, Void, List<User>>() {
//            @Override
//            protected List<User> doInBackground(String... strings) {
////                https://blog.csdn.net/zxl1173558248/article/details/82492655
//                String usernameFn = strings[0];
//                UserDao userDao = database.getUserDao();
//                List<User> byUsername = userDao.getByUsername(usernameFn);
//
//                return byUsername;
//            }
//
//        }.execute().get();

//        final List<User>[][] byUsername = new List<User>[1][1];
//        List<User> byUsername;
//        final List<User>[] byUsername = new List<User>[1];
//        new Object[]{username,userDao}
//        这个可以了  知道怎么匿名 写AsyncTask，知道怎么传参了
//        AsyncTask 匿名 传参
        @SuppressLint("StaticFieldLeak") List<User> byUsername =
                new AsyncTask<Object, Void, List<User>>() {
                    @Override
                    protected List<User> doInBackground(Object... objects) {
//                https://blog.csdn.net/zxl1173558248/article/details/82492655
//                String usernameFn = strings[0];
                        int i = 0;
                        String usernameFn = (String) objects[i++];
                        UserDao userDao = (UserDao) objects[i++];
//                UserDao userDao = database.getUserDao();
                        List<User> byUsername = userDao.getByUsername(usernameFn);
//              byUsername[0] = userDao.getByUsername(usernameFn);
//              这样直接赋值好像不行

//                return byUsername[0];
                        return byUsername;
                    }

                }.execute(new Object[]{username, userDao}).get();


//        List<User> byUsername = userViewModel.findUserByUsername(username);
//这样还是 ui 线程
//        DatabaseTask databaseTask=new DatabaseTask(database);
//        databaseTask.setUsername(username);
//        AsyncTask<Void, Void, List<User>> execute = databaseTask.execute();

//        虽然说这样子可以 但是 每个查询都要写一个类 也太奇怪了
//        List<User> byUsername = execute.get();

        if (byUsername == null) {
            Toast.makeText(this, "查找失败", Toast.LENGTH_SHORT).show();
            return;
        }
//        List<User> byUsername = userRepository.getByUsername(username);
//        https://blog.csdn.net/u012539700/article/details/115833931
//        LiveData
//        if(byUsername[0][0].size()>=1){
        if (byUsername.size() >= 1) {
            Toast.makeText(this, "已经有这个用户", Toast.LENGTH_SHORT).show();
            return;
        }
//        if (byUsername == null || byUsername.size() <= 0) {
//            return;
//        }
//        User user = byUsername.get(0);
//        String savedPassword = user.getPassword();
        User user = new User();
        user.setUsername(username);
        user.setPassword(Security.md5(password));
//        long id = userDao.insert(user);
        userRepository.insert(user);
//     这种没有返回的 倒是可以直接写一个 线程
//        也不行啊 因为具体的东西不一样啊

        Toast.makeText(this, "注册成功 用户名： " + username, Toast.LENGTH_SHORT).show();
        Intent intent = new Intent(this, LoginActivity.class);
        startActivity(intent);

    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {

            case R.id.btn_register:
                try {
                    register();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.btnTestDb:
//                testDb();
                break;

        }
    }
}
